<template>
  <div class="summary_of_consumption">
    <el-form
      :inline="true"
      :model="elform"
      class="demo-form-inline"
      size="mini"
    >
      <el-form-item label="日期:" label-width="40px">
        <el-date-picker
          v-model="Timevalue[0]"
          value-format="yyyy-MM-dd"
          placeholder="选择日期时间"
          style="width: 180px"
        ></el-date-picker>
        <span>至</span>
        <el-date-picker
          v-model="Timevalue[1]"
          value-format="yyyy-MM-dd"
          placeholder="选择日期时间"
          style="width: 180px"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="钱包:" label-width="40px">
        <el-select
          v-model="consumeWalletNo"
          placeholder="请选择"
          size="mini"
          clearable
        >
          <el-option
            v-for="item in paylist"
            :key="item.walletNo"
            :label="item.walletName"
            :value="item.walletNo"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="onSubmit"
          size="mini"
          icon="el-icon-search"
          >查询</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-popover width="500" placement="top" trigger="click">
          <!-- <el-button slot="reference" size="mini" type="primary" icon="el-icon-edit-outline">自定义</el-button> -->
        </el-popover>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="onExport"
          size="mini"
          icon="el-icon-document-copy"
          >导出</el-button
        >
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="printJS"
          size="mini"
          icon="el-icon-printer"
          >打印</el-button
        >
      </el-form-item>
    </el-form>
    <div class="tablemian" ref="tablemian" id="tablemian">
      <!-- 转化后 -->
      <el-table
        border
        :data="transData"
        :span-method="objectSpanMethod"
        :header-cell-style="headFirst"
        :cell-style="headFirst_col"
        :row-style="{ height: 0 + 'px' }"
        v-loading="loading"
      >
        <!--  height="60vh"-->
        <el-table-column
          v-for="(item, index) in transTitle"
          :label="item"
          :key="index"
          align="center"
          :width="index == 0 || index == 1 ? '110px' : '116px'"
        >
          <template slot-scope="scope">{{ scope.row[index] }}</template>
        </el-table-column>
      </el-table>
      <div class="floor">
        <div>复核：</div>
        <div>制表人：{{ loginName }}</div>
        <div style="text-align: right">
          制表日期：{{ getNowTime("yy-mm-dd hh:mm:ss") }}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 钱包列表选项
      paylist: [],
      // 当前选项
      consumeWalletNo: "",
      elform: {},
      Timevalue: [],
     
      loading: false,
      // originData 为后端原始正常的数据, 此数据按正常表格展示 一行一行的数据
      // 保证数组里每一个对象中的字段顺序, 从上到下 一次对应显示表格中的从左到右
      originData: [
        {
          groupGuid: "5aeef1f0-e742-4d7e-ba24-28c04c34cd0b",
          groupName: "单位默认分组",
          cardUserCount: 0,
          cardBalance: 0,
          cardCostBalance: 0,
          cardCashBalance: 0,
          cardManageBalance: 0,
          returnUserCount: 0,
          returnRealityBalance: 0,
          returnCashBalance: 0,
          returnManageBalance: 0,
          rechargeUserCount: 0,
          localAdjustAmount: 0,
          aliAdjustAmount: 0,
          vxAdjustAmount: 0,
          otherAdjustAmount: 0,
          machineAdjustAmount: 0,
          platformAdjustAmount: 0,
          drawUserCount: 0,
          drawExpenditure: 0,
          minusExpenditure: 0,
          replacementUserCount: 0,
          replacementCostBalance: 0,
          replacementCashBalance: 0,
          profitLossUserCount: 0,
          profitLossBalance: 0,
          badDebUserCount: 0,
          badDebCashBalance: 0,
          successExpenditureCount: 0,
          timesExpenditureCount: 0,
          expenditureCount: 0,
          expenditureBalance: 0,
          sumIncomeBalance: null,
          sumCardBalance: null,
          sumExpenditureBalance: null,
        },
      ],
      // 第一列标题
      originTitle: [
        "发卡",
        "",
        "",
        "",
        "",
        // "",
        "退卡",
        "",
        "",
        "",
        "充值",
        "",
        "",
        "",
        "",
        "",
        "",
        "减款",
        "",
        "",
        "补卡",
        "",
        "",
        // "损益",
        // "",
        // "坏账",
        // "",
        "储蓄消费",
        "计次消费",
        "营业总收入",
        "",
        "收入",
        "",
        "支出",
      ],
      // 第二列标题
      originTitle2: [
        // 发卡
        "人次",
        "收工本费",
        "收押金",
        "收管理费",
        "预存款",
        // "退卡",
        "人次",
        "退款",
        "退押金",
        "退管理费",
        // 充值
        "人次",
        "卡务中心充值",
        "充值机充值",
        "支付宝充值",
        "微信充值",
        "第三方充值",
        "平台无卡充值",
        // "减款",
        "人次",
        "卡务中心减款",
        "平台无卡减款",
        // 补卡
        "人次",
        "收工本费",
        "收押金",
        // // "损益",
        // "人次",
        // "金额",
        // // "坏账",
        // "人次",
        // "金额",
        // "储蓄消费",
        "人次",
        // "计次消费",
        "人次",
        // "营业总收入",
        "人次",
        "金额",
        "帐",
        "卡费",
        "帐",
      ], // originTitle 该标题为 正常显示的标题, 数组中的顺序就是上面数据源对象中的字段标题对应的顺序
      // transTitle 该标题为转化后的标题, 注意多一列,  因为原来的标题变成了竖着显示了, 所以多一列标题, 第一个为空即可
      transTitle: ["栏目", ""],
      // 最终渲染数据
      transData: [],
      filename: "卡务汇总表",
      searchInfo: {},
    };
  },
  created() {
    this.Timevalue = [this.getNowTime("yy-mm-dd"), this.getNowTime("yy-mm-dd")];
    this.loginName = sessionStorage.getItem("username");
    // 获取钱包列表
    this.getPayNumber();
    // 获取数据
    this.getInfo();
  },
  computed: {
    changeschoolid: {
      get() {
        return this.$store.state.user.changeschoolid;
      },
    },
  },
  methods: {
    printJS() {
      // 样式
      let style = `@media print { 
       .floor{
        opacity:1;
        margin-top:40px;
        display: flex;
      }
        .floor div{
          flex:1;
        }
        .floor div:last-child{
        text-align:right;
        flex:2;
      }
        table
          {
            border-collapse:collapse;
          }
        th,td
          {
            border: 1px solid #ccc;
            word-wrap:break-word;
            word-break:normal; 
            padding-left:9px;
          }
          td{
            padding-left:15px;
            display:table-cell; vertical-align:middle;
            text-align:center
          }
          th{
            border-bottom:0;
            border-right:0;
          }
          .headerT{
            width:1000px;
          }
      `;
      // 标题宽度
      for (let l = 0; l < 15; l++) {
        if (this.transTitle.length == l + 4) {
          style += `.headerT{width:${490 + l * 125}px;} `;
          if (l + 4 == 4) {
            style += `.headerT div{font-size:14px} `;
          }
          style += `.floor{width:${490 + l * 125}px !important; }`;
        }
      }
      // 去除多余的表格
      for (let i = this.transTitle.length; i > 3; i--) {
        console.log(this.originTitle2.length);
        style += `tr:nth-child(${this.originTitle2.length}) td:nth-child(${i}) {border: 0;}`;
        style += `tr:nth-child(${
          this.originTitle2.length - 1
        }) td:nth-child(${i}) {border: 0;}`;
        style += `tr:nth-child(${
          this.originTitle2.length - 2
        }) td:nth-child(${i}) {border: 0;}`;
      }
      style += `tr:nth-child(1) th:nth-child(${
        this.transTitle.length + 1
      }) {border: 0;border-left:1px solid #ccc;}`;
      style += `tr:nth-child(${
        this.originTitle2.length - 1
      }) td:nth-child(3) {border: 0;}`;
      style += "}";
      const title = " 卡务汇总表";
      this.unitName = sessionStorage.getItem("unitName");
      // 打印
      this.$printJS({
        // 眉头
        documentTitle: `${this.unitName}`,
        // 标题
        header: this.printHeader(
          title,
          this.unitName,
          `${this.Timevalue[0]} 至 ${this.Timevalue[1]}`
        ),
        // 打印节点的id
        printable: "tablemian",
        // 打印类型
        type: "html",
        // 样式
        style,
      });
    },
    // 数据处理
    getInfo() {
      // 行数据排序，数据改动位置在此处更改
      let titleArr = [
        /* 发卡*/
        // "人次",
        "cardUserCount",
        // "收工本费",
        "cardCostBalance",
        // "收押金",
        "cardCashBalance",
        // "收管理费",
        "cardManageBalance",
        // "预存款",
        "cardBalance",
        /* "退卡",*/
        // "人次",
        "returnUserCount",
        // "退款",
        "returnRealityBalance",
        // "退押金",
        "returnCashBalance",
        // "退管理费",
        "returnManageBalance",
        /* 充值*/
        // "人次",
        "rechargeUserCount",
        // "卡务中心充值",
        "localAdjustAmount",
        // "充值机充值",
        "machineAdjustAmount",
        //// "手机充值",
        // "appAdjustAmount",
        // 支付宝存款
        "aliAdjustAmount",
        // 微信存款
        "vxAdjustAmount",
        // 第三方存款
        "otherAdjustAmount",
        // "平台无卡充值",
        "platformAdjustAmount",
        /* "减款", */
        // "人次",
        "drawUserCount",
        // "卡务中心减款金额",
        "drawExpenditure",
        //无卡减款金额
        "minusExpenditure",
        /* 补卡*/
        // "人次",
        "replacementUserCount",
        // "收工本费",
        "replacementCostBalance",
        // "收押金",
        "replacementCashBalance",
        // /* "损益",*/
        // // "人次",
        // "profitLossUserCount",
        // // "金额",
        // "profitLossBalance",
        // /* "坏账", */
        // // "人次",
        // "badDebUserCount",
        // // "金额",
        // "badDebCashBalance",
        /* "储蓄消费",*/
        // "人次",
        "successExpenditureCount",
        // /* "计次消费",*/
        // // "人次",
        "timesExpenditureCount",
        /* "营业总收入",*/
        // "人次",
        "expenditureCount",
        // "金额",
        "expenditureBalance",
        /**收入 */
        // 帐
        "sumIncomeBalance",
        // 卡费
        "sumCardBalance",
        /**支出 */
        // 帐
        "sumExpenditureBalance",
      ];
      // 数组按矩阵思路, 变成转置矩阵
      let matrixData = this.originData.map((row) => {
        let arr = [];
        for (let key in row) {
          titleArr.map((item, index) => {
            if (key == titleArr[index]) {
              arr[index] = row[key];
            }
          });
        }
        return arr;
      });
      // 加入标题拼接最终的数据
      this.transData = matrixData[0].map((col, i) => {
        return [
          this.originTitle[i],
          this.originTitle2[i],
          ...matrixData.map((row) => {
            return row[i];
          }),
        ];
      });
      console.log(this.transData);
    },
    // 获取钱包
    getPayNumber() {
      this.paylist = [];
      this.$http({
        url: this.$http.adornUrl("/unit/unit-wallet-info-list"),
        method: "post",
        data: this.$http.adornData({
          messageContent: { unitGuid: this.changeschoolid },
          messageType: 0,
        }),
      }).then(({ data }) => {
        if (data.messageCode == 200) {
          data.messageContent.map((item) => {
            if (Number(item.walletNo) != 100) {
              this.paylist.push(item);
            }
          });
          console.log(this.paylist);
        } else {
          this.$message({
            showClose: true,
            message: data.errorMessage,
            type: "error",
          });
        }
      });
    },
    onSubmit() {
      this.searchInfo = {};
      this.getgatherlis();
    },
    // 请求拿到数据
    getgatherlis() {
      // 需要分转元的字段
      let amountyuaArr = [
        "cardBalance",
        "cardCostBalance",
        "cardCashBalance",
        "cardManageBalance",
        "returnRealityBalance",
        "returnCashBalance",
        "returnManageBalance",
        "localAdjustAmount",
        "machineAdjustAmount",
        // "appAdjustAmount",
        // 支付宝存款
        "aliAdjustAmount",
        // 微信存款
        "vxAdjustAmount",
        // 第三方存款
        "otherAdjustAmount",
        "platformAdjustAmount",
        "drawExpenditure",
        "minusExpenditure",
        "replacementCostBalance",
        "replacementCashBalance",
        "profitLossBalance",
        "badDebCashBalance",
        "expenditureBalance",
        //  // 帐
        // "sumIncomeBalance",
        // // 卡费
        // "sumCardBalance",
        // /**支出 */
        // // 帐
        // "sumExpenditureBalance"
      ];
      this.searchInfo.unitGuid = this.changeschoolid;
      if (this.Timevalue !== null) {
        this.searchInfo.startDate = this.Timevalue[0];
        this.searchInfo.endDate = this.Timevalue[1];
      }
      this.searchInfo.walletNo = this.consumeWalletNo;
      this.loading = true;
      this.$http({
        url: this.$http.adornUrl("/terminal/consume/consume-gather-search"),
        method: "post",
        data: this.$http.adornData({
          messageContent: this.searchInfo,
          messageType: 0,
        }),
      }).then(({ data }) => {
        this.loading = false;
        if (data.messageCode == 200) {
          let messageContent = data.messageContent;
          if (messageContent) {
            this.originData = [];
            this.transTitle = ["栏目", ""];
            messageContent.forEach((item, index) => {
              delete messageContent[index].groupGuid;
              this.transTitle.push(item.groupName);
              delete messageContent[index].groupName;
              // 金额分转元
              amountyuaArr.map((key) => {
                item[key] = this.amountyua(item[key]);
                // if(key == 'sumIncomeBalance'){
                //   item[key] = item[key]
                //   // + `(发卡预存款 + 主钱包存款金额 + 充值机充值 + 在线充值)`
                // }else if(key == 'sumCardBalance'){
                //   item[key] = item[key] + '(2)'
                // }else if(key == 'sumExpenditureBalance'){
                //   item[key] = item[key] + '(3)'
                // }
              });
              this.originData.push(item);
              // 数据处理
              this.getInfo();
            });
          }
        } else {
          this.$message.error(data.errorMessage);
        }
      });
      console.log(this.originData);
    },
    // 列合并
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (rowIndex === 0) {
          return {
            rowspan: 5,
            colspan: 1,
          };
        } else if (rowIndex === 5) {
          return {
            rowspan: 4,
            colspan: 1,
          };
        } else if (rowIndex === 9) {
          return {
            rowspan: 7,
            colspan: 1,
          };
        } else if (rowIndex === 16) {
          return {
            rowspan: 3,
            colspan: 1,
          };
        } else if (rowIndex === 19) {
          return {
            rowspan: 3,
            colspan: 1,
          };
        } else if (rowIndex === 22) {
          return {
            rowspan: 1,
            colspan: 1,
          };
        } else if (rowIndex === 23) {
          return {
            rowspan: 1,
            colspan: 1,
          };
        } else if (rowIndex === 24) {
          return {
            rowspan: 2,
            colspan: 1,
          };
        } else if (rowIndex === 26) {
          return {
            rowspan: 2,
            colspan: 1,
          };
        }
        else if (rowIndex === 28) {
          return {
            rowspan: 1,
            colspan: 1,
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          };
        }
      } else if (columnIndex === 1) {
        return {
          rowspan: 1,
          colspan: 1,
        };
      } else {
        if (
          rowIndex === this.transData.length - 1 ||
          rowIndex === this.transData.length - 2 ||
          rowIndex === this.transData.length - 3
        ) {
          console.log(this.transTitle.length - 2);
          return {
            rowspan: 1,
            colspan: this.transTitle.length - 2,
          };
        }
        return {
          rowspan: 1,
          colspan: 1,
        };
      }
    },
    // 表头样式
    headFirst({ row, colunm, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return { background: "#45c2b5", color: "#fff" };
      }
    },
    // 列样式
    headFirst_col({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 || columnIndex === 1) {
        // 指定列号
        return {
          fontWeight: "bold",
          fontSize: "12px",
          padding: "3px",
          color: "#000",
        };
      } else {
        if (
          rowIndex === this.transData.length - 1 ||
          rowIndex === this.transData.length - 2 ||
          rowIndex === this.transData.length - 3
        ) {
          return {
            textAlign: "left",
            padding: "0px",
            height: "0px",
          };
        }
        return { padding: "3px" };
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    onExport() {
      let arr = JSON.parse(JSON.stringify(this.transData));
      let obj = arr.map((item, index) => {
        return {
          ...item,
        };
      });
      console.log(obj);
      const nowtime = this.getimeto();
      require.ensure([], () => {
        let length = this.originTitle2.length;
        let multiHeader = [];
        let merges = [
          "A1:B1",
          "A2:A6",
          "A7:A10",
          "A11:A17",
          "A18:A20",
          "A21:A23",
          "A25:A25",
          "A26:A27",
          "A28:A29",
          "A30:A30",
          "C28:F28",
          "C29:F29",
          "C30:F30",
        ];
        const tHeader = this.transTitle;
        const filterValArr = [];
        const { export_json_to_excel } = require("../../excel/Export2Excel");
        const filterVal = Object.keys(obj[0]);
        const list = obj;
        const data = this.formatJson(filterVal, list);
        export_json_to_excel({
          multiHeader,
          header: tHeader,
          data,
          merges,
          filename: this.filename + nowtime,
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.floor {
  opacity: 0;
  width: 2000px;
  display: flex;
}
.floor div {
  flex: 1;
}
#table {
  transform: scale(0.5, 0.5);
}
.summary_of_consumption {
  padding: 10px;
  .el-table__row .el-table__row--level-1 {
    background-color: #e5e9f2;
  }
  .demo-form-inline,
  .demo-form-inline1 {
    /deep/.el-form-item__label {
      padding-right: 5px;
    }
    .el-form-item {
      margin-bottom: 5px;
    }
    .el-date-editor.el-input,
    .el-date-editor.el-input__inner {
      width: 330px;
    }
  }
  .demo-form-inline1 {
    border-bottom: 1px solid #e5e9f2;
    .searchmarigin {
      margin-left: 20px;
    }
  }
  .tablemian {
    //滚动条的宽度
    ::-webkit-scrollbar {
      width: 10px;
      height: 10px;
    }
    //滚动条的滑块
    ::-webkit-scrollbar-thumb {
      background-color: #a1a3a9;
      border-radius: 3px;
    }
    .table-fixed {
      /deep/ .el-table__fixed {
        height: 100% !important; //设置高优先，以覆盖内联样式
      }
    }
  }
  .page {
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>

